from selenium import webdriver
import time
import requests
import json
import base64
import urllib

browser = webdriver.Chrome('D:\\资料\\第六个月\\chromedriver.exe')  # 建立浏览器对象

browser.get('http://localhost:8080/register')  # 打开网页

# time.sleep(3)
myimg = browser.find_element_by_xpath('//*[@id="app"]/div/section/div/p[4]/img')  # 选择元素
# print(myimg)

# 截取元素图
myimg.screenshot('register.png')

# browser.get_screenshot_as_file('register.png')  # 截取屏幕


# 请求百度接口
res = requests.get(
    'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=8MGrAEGK1q3R5iMYq6rzZPZT&client_secret=i19G1sD15nI3oqgkMxgCzmZb0Mob34GG')

# 转码
res = json.loads(str(res.text))
# print(res)
token = res['access_token']

# 识别图像
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token

# 构造头部
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

# 构造图片
img = open('./register.png', 'rb')
temp_img = img.read()
img.close()

# 构建参数
data = {'image': base64.b64encode(temp_img)}

# 编码
data = urllib.parse.urlencode(data)
# print(data)

# 发送请求
res = requests.post(url=url, data=data, headers=headers)
res = json.loads(res.text)
imagename = res['words_result'][0]['words']
imagename = imagename.split(' ')
imagename_new = ''
for i in imagename:
    imagename_new += i

browser.find_element_by_xpath('//*[@id="app"]/div/section/div/p[1]/input').send_keys('23333')
time.sleep(1)
browser.find_element_by_xpath('//*[@id="app"]/div/section/div/p[2]/input').send_keys('233')
time.sleep(1)
browser.find_element_by_xpath('//*[@id="app"]/div/section/div/p[3]/input').send_keys(imagename_new)
time.sleep(1)
browser.find_element_by_xpath('//*[@id="app"]/div/section/div/p[6]/button[1]/span').click()
time.sleep(1)
browser.close()
